<template>
  <div class="count">
    <div class="count-value">
      <div v-for="x in toggleColck(count)">
        <div v-if="x == ':'"> : </div>
        <div v-else>
          <blacknum :num="x" />
        </div>
      </div>
    </div>
    <div class="count-content">
      <div v-if="working">
        <el-button @click="pause" type="danger">暂停</el-button>
      </div>
      <template v-else>
        <template v-if="count == 0">
          <div>
            选择时间
          </div>
          <div>
            <el-select v-model="total" style="width: 100px;">
              <el-option v-for="x in timeList" :value="x.value" :label="x.label"></el-option>
            </el-select>
          </div>
          <div>
            <el-button @click="start" type="primary">开始计时</el-button>
          </div>
        </template>
        <div v-else>
          <el-button @click="restart" type="success">继续计时</el-button>
        </div>
      </template>
      <div>
        <el-button @click="reset">重置</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance, onUnmounted } from 'vue';
import blacknum from '../common/blacknum.vue'
const { proxy } = getCurrentInstance()
let timer = null
const count = ref(0)
const total = ref(3)
const working = ref(false)
const timeList = [
  { label: '三秒', value: 3 },
  { label: '十秒', value: 10 },
  { label: '三十秒', value: 30 },
  { label: '一分钟', value: 60 },
  { label: '三分钟', value: 180 },
  { label: '五分钟', value: 300 },
  { label: '三十分钟', value: 1800 },
  { label: '一小时', value: 3600 },
  { label: '二小时', value: 7200 },
]

function reduce() {
  if (count.value == 0) {
    proxy.$element.success('计时结束')
    clearInterval(timer)
    working.value = false
    return
  }
  count.value -= 1
}

function start() {
  working.value = true
  count.value = total.value
  timer = setInterval(() => {
    reduce()
  }, 1000);
}

function restart() {
  working.value = true
  timer = setInterval(() => {
    reduce()
  }, 1000);
}

function pause() {
  working.value = false
  clearInterval(timer)
}

function zero(num) {
  return num >= 10 ? num : '0' + num
}

function toggleColck(seconds) {
  let arr = []
  if (seconds >= 0) {
    let h = parseInt(seconds / 3600)
    let min = parseInt((seconds - h * 3600 ) / 60)
    let sec = seconds - h * 3600 - min * 60
    let str = `${zero(h)}:${zero(min)}:${zero(sec)}`
    // console.log(str)
    arr = str.split('')
  }

  return arr
}

function reset() {
  clearInterval(timer)
  working.value = false
  count.value = 0
}

onUnmounted(() => {
  clearInterval(timer)
})

</script>
<style scoped lang="scss">
.count-content {
  display: flex;

  >div {
    margin-right: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.count-value {
  display: flex;
  font-weight: 700;
  font-size: 120px;
  margin: 20px;

  >div {
    >div {
      margin-right: 10px;
    }
  }
}
</style>
